package util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	//默认的应用名
	private static String DEFAULT_PATH = "/servletdang";
	//默认的保存时间
	private static int DEFAULT_AGE = 24 * 60 * 60;
	
	private CookieUtil(){}
	
	/**
	 * 添加一个cookie
	 * @param name
	 * @param value
	 * @param path
	 * @param age
	 * @param response
	 * @throws UnsupportedEncodingException 
	 */
	public static void addCookie(String name, String value, String path, int age,
			HttpServletResponse response) throws UnsupportedEncodingException{
		if (path == null || "".equals(path.trim())) {
			path = DEFAULT_PATH;
		}
		Cookie cookie = new Cookie(name, URLEncoder.encode(value, "utf-8"));
		cookie.setMaxAge(age);
		cookie.setPath(path);
		response.addCookie(cookie);
	}
	
	/**
	 * 添加一个cookie
	 * @param name
	 * @param value
	 * @param age
	 * @param response
	 * @throws UnsupportedEncodingException
	 */
	public static void addCookie(String name, String value, int age, HttpServletResponse response) throws UnsupportedEncodingException{
		addCookie(name, value, DEFAULT_PATH, age, response);
	}
	
	/**
	 * 添加一个cookie
	 * @param name
	 * @param value
	 * @param response
	 * @throws UnsupportedEncodingException 
	 */
	public static void addCookie(String name, String value, HttpServletResponse response) throws UnsupportedEncodingException{
		addCookie(name, value, DEFAULT_PATH, DEFAULT_AGE, response);
	}
	
	/**
	 * 根据cookie的名字，查找cookie的值；如果没找到，返回null
	 * @param name
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static String findCookie(String name, HttpServletRequest request) throws UnsupportedEncodingException{
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie c = cookies[i];
				if (c.getName().equals(name)) {
					return URLDecoder.decode(c.getValue(), "utf-8");
				}
			}
		}
		return null;
	}
	
	/**
	 * 删除cookie
	 * @param name
	 * @param response
	 */
	public static void deleteCookie(String name, HttpServletResponse response){
		Cookie cookie = new Cookie(name, "");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}
}
